package com.imaker.service;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.imaker.dao.BaseDao;
import com.imaker.domain.RoleInfo;
import com.imaker.domain.UserInfo;
import com.imaker.domain.UserRoleInfo;

 /**
 * <p>程序名称：      UserRoleService.java</p>
 * <p>程序说明：       TODO</p>
 * <p>版权信息：       Copyright mayonghua</p>
 * 
 * @author：          mayonghua
 * @version：         Ver 0.1
 */
@Service
public class UserRoleService implements IService {
	private BaseDao<UserRoleInfo> userRoleDAO = null;
	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		userRoleDAO = new BaseDao<UserRoleInfo>(sessionFactory,UserRoleInfo.class);
	}
	
	
	/**
	 * 按照用户查询
	 * @param userInfo
	 * @return
	 * @throws Exception
	 */
	public List<UserRoleInfo> findByUser(UserInfo userInfo) throws Exception{
		String hql = "from UserRoleInfo ur where ur.user.id = ? and ur.state = ?";
		return userRoleDAO.find(hql,userInfo.getId(),"T");
	}
	
	/**
	 * 更新
	 * @param id
	 * @param flag
	 */
	public void update(List<String> idList,String flag,UserInfo userInfo) throws Exception{
		
		for(String id : idList){
			String hql = "from UserRoleInfo ur where ur.user.id = ? and ur.role.id =?";
			List<UserRoleInfo> list = userRoleDAO.find(hql,userInfo.getId(),id);
			if("T".equals(flag)){
				if(list!=null&&list.size()>0){
					UserRoleInfo ur = list.get(0);
					ur.setState("T");
					userRoleDAO.update(ur);
				}else {
					RoleInfo role = new RoleInfo();
					role.setId(id);
					UserRoleInfo userRole = new UserRoleInfo();
					userRole.setRole(role);
					userRole.setUser(userInfo);
					userRole.setState("T");
					userRoleDAO.save(userRole);
				}
			}else if("F".equals(flag)){
				if(list!=null&&list.size()>0){
					UserRoleInfo ur = list.get(0);
					ur.setState("F");
					userRoleDAO.update(ur);
				}
			}
		}
	}
	
	
}
